class Snake {

    // 蛇头
    head: HTMLElement
    // 蛇的身体（包括蛇头）
    // bodies: HTMLCollection
    bodies: HTMLCollectionOf<HTMLDivElement>
    // 容器
    element: HTMLElement

    constructor() {
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake > div') as HTMLElement

        this.bodies = this.element.getElementsByTagName('div')
    }

    get X() {
        return this.head.offsetLeft
    }

    get Y() {
        return this.head.offsetTop
    }

    set X(value: number) {

        if (this.X === value) {
            return;
        }

        if (value < 0 || value > 290) {
            throw new Error("蛇撞墙了");
        }
        // 是否掉头
        if (this.bodies[1] && value === this.bodies[1].offsetLeft) {
            if (value > this.X) value = this.X - 10
            else value = this.X + 10
        }

        this.moveBody()
        this.head.style.left = value + 'px'
        this.checkHeadBody()



    }

    set Y(value: number) {

        if (this.Y === value) {
            return;
        }

        if (value < 0 || value > 290) {
            throw new Error("蛇撞墙了");
        }
        // 是否掉头
        if (this.bodies[1] && value === this.bodies[1].offsetTop) {
            if (value > this.Y) value = this.Y - 10
            else value = this.Y + 10
        }

        this.moveBody()
        this.head.style.top = value + 'px'
        this.checkHeadBody()



    }

    addBody() {
        this.element.insertAdjacentHTML('beforeend', '<div></div>')
    }

    moveBody() {
        for (let i = this.bodies.length - 1; i > 0; i--) {
            let X = this.bodies[i - 1].offsetLeft
            let Y = this.bodies[i - 1].offsetTop

            this.bodies[i].style.left = X + 'px'
            this.bodies[i].style.top = Y + 'px'

        }
    }

    checkHeadBody(){
        for(let i = 2;i<this.bodies.length;i++){
            if(this.X === this.bodies[i].offsetLeft && this.Y === this.bodies[i].offsetTop){
                throw new Error("撞到自己了");
            }
        }
    }


}

export default Snake